<!-- 正文开始 -->
<div class="layui-fluid" id="mainSysUser">
    <div class="layui-card">
        <div class="layui-card-header">筛选条件</div>
        <div class="layui-card-body">
            <form class="layui-form layui-form-pane">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-md3 layui-col-sm12 layui-col-xs12">
                        <label class="layui-form-label">用户账号</label>
                        <div class="layui-input-block">
                            <input type="text" name="username" autocomplete="off" placeholder="请输入用户账号"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-col-md3 layui-col-sm12 layui-col-xs12">
                        <label class="layui-form-label">用户昵称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" autocomplete="off" placeholder="请输入用户昵称"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-col-md3 layui-col-sm12 layui-col-xs12">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <select id="queryStateSysUser" name="state"></select>
                        </div>
                    </div>
                    <div class="layui-col-md2 layui-col-sm12 layui-col-xs12">
                        <button class="layui-btn layui-btn-fluid" lay-submit
                                id="querySubmitSysUser" lay-filter="querySubmitSysUser">筛选
                        </button>
                    </div>
                    <div class="layui-col-md1 layui-col-sm12 layui-col-xs12">
                        <button type="reset" class="layui-btn layui-btn-primary layui-btn-fluid">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="layui-card">
        <table id="listSysUser" lay-filter="listSysUser"></table>
    </div>
</div>

<!-- 表格批量工具栏 -->
<script type="text/html" id="listToolbarSysUser">
    <div class="layui-btn-container">
        {{# if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.createOrUpdate.getPermissionUrl("POST"))){ }}
        <a class="layui-btn layui-btn-sm" lay-event="listToolbarSaveSysUser">
            <i class="layui-icon">&#xe61f;</i>添加用户</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.batchResetPwd.getPermissionUrl("PUT"))){ }}
        <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="listToolbarResetPwdRender">
            <i class="layui-icon">&#xe673;</i>重置密码</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.batchUpdateState.getPermissionUrl("PUT"))){ }}
        <a class="layui-btn layui-btn-sm layui-btn-primary" lay-event="listToolbarEnableSysUser">
            <i class="layui-icon">&#x1005;</i>批量启用</a>
        <a class="layui-btn layui-btn-sm layui-btn-primary" lay-event="listToolbarDisableSysUser">
            <i class="layui-icon">&#x1007;</i>批量禁用</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.batchDelete.getPermissionUrl("PUT"))){ }}
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="listToolbarDelSysUser">
            <i class="layui-icon">&#xe640;</i>批量删除</a>
        {{# } }}
    </div>
</script>

<!-- 表格状态模板 -->
<script type="text/html" id="listStateTplSysUser">
    {{#  if(layui.reqEnum.state.normal === d.state){ }}
    <span style="color: #009688;">{{ d.stateStr }}</span>
    {{#  } else if(layui.reqEnum.state.disable === d.state) { }}
    <span style="color: #d2d2d2;">{{ d.stateStr }}</span>
    {{#  } else { }}
    <span>{{ d.state_str }}</span>
    {{#  } }}
</script>

<!-- 表格操作模板 -->
<script type="text/html" id="listToolSysUser">
    {{# if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.setUserRole.getPermissionUrl("PUT"))){ }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="listToolSetSysUserRole"> 用户角色 </a>
    {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.batchResetPwd.getPermissionUrl("PUT"))){ }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="listToolResetPwdRender"> 重置密码 </a>
    {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.createOrUpdate.getPermissionUrl("POST"))){ }}
    <a class="layui-btn layui-btn-xs" lay-event="listToolUpdateSysUser"> 编辑 </a>
    {{# } if(layui.admin.hasPerm(layui.reqApi.admin.sysUser.batchDelete.getPermissionUrl("PUT"))){ }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="listToolDelSysUser"> 删除 </a>
    {{# } }}
</script>

<!-- 新增或者修改 -->
<script type="text/html" id="suContainerSysUser">
    <form lay-filter="suFormSysUser" class="layui-form layui-form-pane">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label red-star-label">用户账号</label>
            <div class="layui-input-block">
                <input name="username" placeholder="请输入用户账号" type="text" class="layui-input" maxlength="64"
                       lay-verType="tips" lay-verify="username"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label red-star-label">用户昵称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入用户昵称" type="text" class="layui-input" maxlength="64"
                       lay-verType="tips" lay-verify="required"/>
            </div>
        </div>
        <div class="layui-form-item" id="company">
            <label class="layui-form-label">所属公司</label>
            <div class="layui-input-block">
                 <select id="companyId" name="companyId" xm-select="companyId">
                 </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">公司职位</label>
            <div class="layui-input-block">
                 <select id="saveOrUpdateTypeEnum" name="type" xm-select="saveOrUpdateTypeEnum"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="border-right: none">用户角色</label>
            <div class="layui-input-block">
                <select id="roleIdList" name="roleIdList" xm-select="roleIdList"></select>
            </div>
        </div>
        <div class="layui-form-item  layui-form-text">
            <label class="layui-form-label layui-btn-fluid">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="suSubmitSysUser" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'table', 'admin', 'setter', 'form', 'reqApi', 'reqEnum', 'promiseReq', 'formSelects'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var admin = layui.admin;
        var setter = layui.setter;
        var form = layui.form;
        var reqApi = layui.reqApi;
        var reqEnum = layui.reqEnum;
        var promiseReq = layui.promiseReq;
        var formSelects = layui.formSelects;

        // 引用对象
        var main = 'mainSysUser'
            , queryState = 'queryStateSysUser'
            , querySubmit = 'querySubmitSysUser'
            , list = 'listSysUser'
            , listToolbar = 'listToolbarSysUser'
            , listToolbarSave = 'listToolbarSaveSysUser'
            , listToolbarSetSysUserRole = 'listToolbarSetSysUserRole'
            , listToolbarResetPwdRender = 'listToolbarResetPwdRender'
            , listToolbarEnable = 'listToolbarEnableSysUser'
            , listToolbarDisable = 'listToolbarDisableSysUser'
            , listToolbarDel = 'listToolbarDelSysUser'
            , listStateTpl = 'listStateTplSysUser'
            , listTool = 'listToolSysUser'
            , listToolSetSysUserRole = 'listToolSetSysUserRole'
            , listToolResetPwdRender = 'listToolResetPwdRender'
            , listToolUpdate = 'listToolUpdateSysUser'
            , listToolDel = 'listToolDelSysUser'
            , suContainer = 'suContainerSysUser'
            , suForm = 'suFormSysUser'
            , suSubmit = 'suSubmitSysUser'
        ;

        var roleIdList = 'roleIdList'
            , suOpen = 'suOpenRole'
        ;

        // 验证
        form.verify({
            username: function (value) {
                if (!new RegExp("^[a-zA-Z]\\w{4,16}$").test(value)) {
                    return '用户账号必须为4-16个中英文字母';
                }
            }
        });

        // 等待框
        admin.showLoading('#' + main, 1, '.5');

        // 字典
        var listStateReq = promiseReq.req({
            url: reqApi.admin.home.enum.restfulFormat({enumName: 'StateEnum'})
            , type: 'get'
            , success: function (rs) {
                var dataList = rs.data;
                var str = '<option value="">请选择</option>';
                for (var i = 0; i < dataList.length; i++) {
                    var data = dataList[i];
                    str += '<option value="' + data.value + '">' + data.msg + '</option>'
                }
                $('#' + queryState).empty();
                $('#' + queryState).append(str);
            }
        });

        //职位字典
        promiseReq.enum({
            enumName:'SysUserTypeEnum',
            container:'querySysUserType'
        });

        // 筛选
        form.on('submit(' + querySubmit + ')', function (obj) {
            admin.showLoading('#' + main, 1, '.5');
            listRender(obj.field);
            return false;
        });

        // 表格筛选触发
        function listQuery() {
            $('#' + querySubmit).click();
        }

        // 执行
        listRender();

        // 表格渲染
        function listRender(param) {
            // 权限设置
            var toolbar = '#' + listToolbar;
            var handle = [{title: '操作', align: "center", templet: '#' + listTool, width: 270, fixed: 'left'}];
            if (!admin.hasPerm(layui.reqApi.admin.sysUser.createOrUpdate.getPermissionUrl("POST"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.batchResetPwd.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.batchUpdateState.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.batchDelete.getPermissionUrl("PUT"))) {
                toolbar = false;
            }
            if (!admin.hasPerm(layui.reqApi.admin.sysUser.createOrUpdate.getPermissionUrl("POST"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.batchResetPwd.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.setUserRole.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.sysUser.batchDelete.getPermissionUrl("PUT"))) {
                handle = []
            }

            // 初始化
            table.render({
                elem: '#' + list
                , toolbar: toolbar
                , headers: {Authorization: setter.getBearerToken()}
                , url: reqApi.admin.sysUser.list
                , cellMinWidth: 150
                , cols: [[].concat(handle).concat([
                    {title: '序号', type: 'numbers', width: 100},
                    {type: 'checkbox', width: 60},
                    {title: '用户编号', field: 'userId', align: 'left',hide:true},
                    {title: '用户角色', field: 'roleNames', align: 'left', minWidth: 200,hide:true},
                    {title: '用户账号', field: 'username', align: 'left'},
                    {title: '用户昵称', field: 'name', align: 'left'},
                    {title: '用户职位', field: 'typeStr', align: 'left'},
                    {title: '状态', field: 'state', align: 'center', templet: '#' + listStateTpl},
                    {title: '修改时间', field: 'gmtModified', align: 'center', minWidth: 180},
                    {title: '创建时间', field: 'gmtCreate', align: 'center', minWidth: 180},
                    {title: '备注', field: 'remark', align: 'left', minWidth: 250}
                ])]
                , where: param
                , done: function () {
                    Promise.all([listStateReq]).finally(function () {
                        form.render();
                        admin.removeLoading('#' + main);
                    });
                }
                , request: {pageName: 'cursor', limitName: 'limit'}
                , parseData: function (rs) {
                    return {"code": rs.code, "msg": rs.msg, "count": rs.data.total, "data": rs.data.records};
                }
                , response: {statusCode: 200}
                , defaultToolbar: ['filter']
                , page: true
                , limit: 50
                , loading: true
                , text: {none: '暂无相关数据'}
            });
        }

        // 监听表格批量工具栏
        table.on('toolbar(' + list + ')', function (obj) {
            switch (obj.event) {
                case listToolbarSave:
                    suRender();
                    break;
                case listToolbarSetSysUserRole:
                    var data = table.checkStatus(list).data;
                    if (0 === data.length) {
                        layer.msg('请勾选要操作的数据', {time: 1000});
                        break;
                    }
                    var idList = [];
                    for (var i in data) {
                        idList[i] = data[i].userId;
                    }
                    sysUserRoleRender(idList);
                    break;
                case listToolbarResetPwdRender:
                    var data = table.checkStatus(list).data;
                    if (0 === data.length) {
                        layer.msg('请勾选要操作的数据', {time: 1000});
                        break;
                    }
                    var idList = [];
                    for (var i in data) {
                        idList[i] = data[i].userId;
                    }
                    resetPwdRender(idList);
                    break;
                case listToolbarEnable:
                    updateStateRender(reqEnum.state.normal);
                    break;
                case listToolbarDisable:
                    updateStateRender(reqEnum.state.disable);
                    break;
                case listToolbarDel:
                    var data = table.checkStatus(list).data;
                    if (0 === data.length) {
                        layer.msg('请勾选要删除的数据', {time: 1000});
                        break;
                    }
                    var idList = [];
                    for (var i in data) {
                        idList[i] = data[i].userId;
                    }
                    delRender(idList);
                    break;
            }
        });

        // 监听表格操作行
        table.on('tool(' + list + ')', function (obj) {
            var id = obj.data.userId;
            switch (obj.event) {
                case listToolSetSysUserRole:
                    sysUserRoleRender([id]);
                    break;
                case listToolResetPwdRender:
                    resetPwdRender([id]);
                    break;
                case listToolUpdate:
                    suRender(id);
                    break;
                case listToolDel:
                    delRender([id]);
                    break;
            }
        });

        // 用户角色
        function sysUserRoleRender(userIdList) {
            var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
            var userId = '';
            if (1 == userIdList.length) {
                userId = '?userId=' + userIdList[0];
            }
            var content = '<form class="layui-form"><div class="layui-form-item">';
            promiseReq.req({
                url: reqApi.admin.role.all + userId
                , success: function (rs) {
                    var dataList = rs.data;
                    for (var i = 0; i < dataList.length; i++) {
                        var data = dataList[i];
                        content += '<div class="layui-inline"><input type="checkbox" name="roleIdList" ' +
                            'title="' + data.roleName + '" value="' + data.roleId + '" lay-skin="primary" ';
                        if (data.checked) {
                            content += 'checked></div>';
                        } else {
                            content += '></div>';
                        }
                    }
                    content += '</div></form>';
                }
            }).then(function () {
                admin.open({
                    title: '用户角色'
                    , type: 1
                    , shadeClose: true
                    , content: content
                    , btn: ['确认选择']
                    , success: function (layero, index) {
                        $(layero).children('.layui-layer-content').css('overflow', 'visible');
                        form.render();
                        layer.close(reqEL);
                    }
                    , yes: function (index) {
                        var roleIdList = new Array();
                        $("input[name='roleIdList']:checked").each(function () {
                            roleIdList.push($(this).val());
                        })
                        new Promise(function (resolve, reject) {
                            if (0 === roleIdList.length) {
                                layer.confirm('由于没有选择角色，所操作的用户角色将会被清空，请确认？', {
                                    skin: 'layui-layer-admin'
                                    , btn: ['确定', '取消']
                                }, function (confirmIndex) {
                                    resolve();
                                    layer.close(confirmIndex);
                                }, function (confirmIndex) {
                                    reject();
                                    layer.close(confirmIndex);
                                });
                            } else {
                                resolve();
                            }
                        }).then(function () {
                            var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                            admin.req({
                                url: reqApi.admin.sysUser.setUserRole
                                , type: 'put'
                                , data: {userIdList: userIdList, roleIdList: roleIdList}
                                , complete: function () {
                                    layer.close(reqEL);
                                }
                                , success: function () {
                                    listQuery();
                                    layer.close(index);
                                    layer.msg('操作成功', {offset: '15px', icon: 1, time: 1000});
                                }
                            });
                        }).catch(function () {
                        })
                    }
                });
            });
        }

        // 启用或者禁用操作
        function updateStateRender(state) {
            var data = table.checkStatus(list).data;
            if (0 === data.length) {
                layer.msg('请勾选要操作的数据', {time: 1000});
                return;
            }
            var idList = [];
            for (var i in data) {
                idList[i] = data[i].userId;
            }
            layer.confirm('确定操作所选信息？', {
                skin: 'layui-layer-admin'
                , btn: ['确定', '取消'] //按钮
            }, function () {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.sysUser.batchUpdateState
                    , type: 'put'
                    , data: {'idList': idList, 'state': state}
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        listQuery();
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 1000});
                    }
                });
            }, function () {
            });
        }

        // 删除操作
        function delRender(idList) {
            layer.confirm('确定删除所选信息？', {
                skin: 'layui-layer-admin'
                , btn: ['确定', '取消']
            }, function () {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.sysUser.batchDelete
                    , type: 'put'
                    , data: idList
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 500});
                        listQuery();
                    }
                });
            }, function () {
            });
        }

        // 重置密码
        function resetPwdRender(idList) {
            layer.confirm('确定重置所选账号的密码？', {
                skin: 'layui-layer-admin'
                , btn: ['确定', '取消']
            }, function () {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.sysUser.batchResetPwd
                    , type: 'put'
                    , data: idList
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 500});
                        listQuery();
                    }
                });
            }, function () {
            });
        }

        // 新增或者修改
        function suRender(id) {
            admin.open({
                id: suOpen
                , type: 1
                , title: id==null?'新增':'修改'
                , shadeClose: true
                , content: $('#' + suContainer).html()
                , success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    admin.showLoading('#' + suOpen, 1, '.5');
                    suSubmitRender(index);
                    
                    //职位字典
                    var sysUserTypeEnumReq = promiseReq.enum({enumName: 'SysUserTypeEnum',container:'saveOrUpdateTypeEnum'})

                    //所属公司
                    var mainCompanyListReq = promiseReq.req({
                        url: reqApi.admin.mainCompany.all
                        , success: function (rs) {
                            var dataList = rs.data;
                            var str = '<option value="">请选择</option>';
                            for (var i = 0; i < dataList.length; i++) {
                                var data = dataList[i];
                                str += '<option value="' + data.id + '">' + data.companyName + '</option>'
                            }
                            $('#companyId').empty();
                            $('#companyId').append(str);
                        }
                    });

                    //用户角色
                    var roleIdListReq = promiseReq.req({
                        url: reqApi.admin.role.all
                        , success: function (rs) {
                            var dataList = rs.data;
                            var str = '<option value="">请选择</option>';
                            for (var i = 0; i < dataList.length; i++) {
                                var data = dataList[i];
                                str += '<option value="' + data.roleId + '">' + data.roleName + '</option>'
                            }
                            $('#' + roleIdList).empty();
                            $('#' + roleIdList).append(str);
                        }
                    });

                    if (id) {
                        var infoReq = promiseReq.req({
                            url: reqApi.admin.sysUser.get.restfulFormat({id: id})
                            , success: function (rs) {
                                var data = rs.data;
                                form.val(suForm, {
                                    "userId": data.userId
                                    , "username": data.username
                                    , "name": data.name
                                    , "remark": data.remark
                                    , "companyId": data.companyId
                                    , "type": data.type
                                });
                                Promise.all([roleIdListReq,mainCompanyListReq,sysUserTypeEnumReq]).finally(function () {
                                    formSelects.render(roleIdList, {init: data.roleIdList});
                                });
                            }
                        });
                        Promise.all([infoReq, roleIdListReq,mainCompanyListReq,sysUserTypeEnumReq]).finally(function () {
                            admin.removeLoading('#' + suOpen);
                            form.render();
                        });
                    } else {
                        Promise.all([roleIdListReq,mainCompanyListReq,sysUserTypeEnumReq]).finally(function () {
                            formSelects.render(roleIdList, {init: []});
                            admin.removeLoading('#' + suOpen);
                            form.render();
                            form.val(suForm, {"companyId": setter.getUser().companyId});
                        });
                    }
                }
            });
        }

        // 初始化新增或者修改提交
        function suSubmitRender(index) {
            form.on('submit(' + suSubmit + ')', function (obj) {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                obj.field.roleIdList = formSelects.value(roleIdList, 'val');
                admin.req({
                    url: reqApi.admin.sysUser.createOrUpdate
                    , type: 'post'
                    , data: obj.field
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 500});
                        layer.close(index);
                        listQuery();
                    }
                });
                return false;
            });
        }
    });
</script>